const cloud = require('wx-server-sdk');


//清理5天之前的二维码信息
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {

  const wxContext = cloud.getWXContext()

    
  const res = await db.collection("user").where({openid:wxContext.OPENID,status:0}).get()

  if(res.data.length == 0)
  {
      return {
        code:401,
        data:{},
        msg:"no privilege"
      }
  }
  else
  {
    let k = new Date()
    let timestamp = new Date(k.valueOf()- 24*60*60*15*1000).valueOf()
    const resul = await db.collection("QRcode").where({timestamp:_.lt(timestamp)}).get()

    let data = resul.data

    if(data.length == 0)
    {
      return {
        code:404,
        data:{removed:0},
        msg:"no QRcode"
      }
    }
    let filelist = []

    for(let i in data)
    {
      filelist.push(data[i].path)
    }
    
    const deleteResult = await cloud.deleteFile({
      fileList:filelist
    })

    const resu = await db.collection("QRcode").where({timestamp:_.lt(timestamp)}).remove()

    if(resu.errMsg == "collection.remove:ok")
    {
      return {
        code:200,
        data:{
          databaseRemoved:resu.stats.removed,
          fileRemoved:deleteResult.fileList
        },
        msg:"success"
      }
    }
    else
    {
      return {
        code:500,
        data:{
          msg:resu,
        },
        msg:"fail"
      } 
    }
  }
};
